// 头部
import React , {useEffect, useState} from 'react'
import { useNavigate } from 'react-router-dom';

import logoImg from '../assets/logo.png'
import defaultAvatar from '../assets/defaultAvayar.jpg'

import { CaretDownOutlined } from '@ant-design/icons';
import { Dropdown, Menu, Space,message } from 'antd';

import { connect } from 'react-redux';


function Header(props) {

    const [avatar,setAvatar] = useState(defaultAvatar)
    const [username,setUsername] = useState("游客")
    const navigate = useNavigate()
    // 模拟componentDidMount
    useEffect(()=>{
        // 替换默认名字和图像
        let username1 = localStorage.getItem('username')
        let avatar1 = localStorage.getItem('avatar')
        if(username1){
            setUsername(username1)
        }
        if(avatar1){
            setAvatar('http://47.93.114.103:6688/' + avatar1)
        } 
        
    },[props.mykey])

    // 退出登录
    const logout =() =>{
        localStorage.clear(); //清除localStorage中的数据
        message.success('退出成功，即将返回登录页')
        setTimeout(()=>{
            navigate('/login');
        },1000)
    }
    const menu = (
        <Menu
            items={[
                {
                key: '1',
                label: (
                    // <a target="_blank" rel="noopener noreferrer" href="https://www.antgroup.com">
                    // 1st menu item
                    // </a>
                    <a href='#'>修改资料</a>
                ),
                },
                {
                    type: 'divider',
                },
                {
                key: '2',
                label: (
                    // <a target="_blank" rel="noopener noreferrer" href="https://www.aliyun.com">
                    // 2nd menu item (disabled)
                    // </a>
                    <span onClick= {logout}> 退出登录 </span>
                    
                ),
                },
            ]}
            />
        );

    return (
        <header>
            <img src={logoImg} alt='' className='logo' />
            <div className="right">
                <Dropdown overlay={menu}>
                    <a className='ant-dropdown-link' onClick={(e) => e.preventDefault()}>
                    <Space>
                        <img src={avatar} className="avatar" alt="" />
                        <span>{username}</span>
                        <CaretDownOutlined />
                    </Space>
                    </a>
                </Dropdown>
            </div>
        </header>
    )
}


const mapStateToProps = (state) => {
    return {
        mykey: state.mykey
    }
}

export default connect(mapStateToProps)(Header)
